<template>
  <el-dialog
    v-model="dialogVisible"
    title="添加海报"
    align-center
    width="480"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    @close="closeDialog"
  >
    <el-upload
      class="upload-demo"
      ref="uploadImg"
      :show-file-list="false"
      drag
      multiple
      :auto-upload="false"
      :on-change="
        (file, fileList) => {
          handleAvatarChangeIcon(file, fileList);
        }
      "
    >
      <el-icon class="el-icon--upload">
        <img src="@/assets/images/mall/upload.png" alt="" />
      </el-icon>
      <div class="el-upload__text"><em style="line-height: 24px">上传文件</em></div>
      <p>建议图片尺寸：1920*550px，大小不超过5MB</p>
    </el-upload>
    <div class="file-list mt22">
      <div class="list-item" v-for="(item, index) in FileList" :key="index">
        <div class="left">
          <img v-if="item.img" :src="item.img" alt="" />
          <el-icon class="img" v-else><Loading /></el-icon>
          <div class="ml13">
            <p class="mb7">{{ item.name }}</p>
            <el-input v-model="item['linkUrl']" placeholder="请输入链接地址" />
          </div>
        </div>

        <el-icon @click="delFileList(item, index)"><CloseBold /></el-icon>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button :disabled="!imgIsReady" type="primary" @click="submit">确认上传</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, nextTick } from "vue";
import useMultipartOssStore from "@/store/modules/multipartOssStore.js";
const ossStore = useMultipartOssStore();
import { ElMessage } from "element-plus";
import { _debounce } from "@/utils/index"; //防抖，多次频繁触发时，只执行最后一次
import { CloseBold, Loading } from "@element-plus/icons-vue";
import { getFolder } from "@/utils/index";

const emit = defineEmits(["submit", "close"]);
const props = defineProps({
  optionInfo: {
    type: Object,
    default: () => {
      return {
        isShow: false
      };
    }
  }
});
const dialogVisible = ref(false);
const FileList = ref([]);
const uploadImg = ref();

watch(
  () => props.optionInfo,
  val => {
    dialogVisible.value = val.isShow;
  },
  { deep: true }
);

const closeDialog = () => {
  //   resetForm(); //清空表单
  uploadImg.value.clearFiles();
  FileList.value = [];
  emit("close");
};
const submit = async () => {
  // for (let i = 0; i < FileList.value.length; i++) {
  //   if (!FileList.value[i].linkUrl) {
  //     return ElMessage({
  //       message: "请完整填写链接地址",
  //       type: "error"
  //     });
  //   }
  // }
  emit("submit", FileList.value);
  uploadImg.value.clearFiles();
  FileList.value = [];
};

//====================================图片上传========================================================================================

const imgIsReady = ref(false);
const handleAvatarChangeIcon = _debounce(async (file, fileList, type = "img") => {
  //选中文件触发的change事件
  // console.log(fileList);
  imgIsReady.value = false;
  const flag = await fileType(type, type === "img" ? fileList : [file]);
  if (!flag) {
    const errorFile = [];
    const successFile = [];
    if (type === "img") {
      ElMessage({
        message: "只能上传jpeg，jpg，png图片文件，大小不超过5M",
        type: "error",
        offset: 60
      });
      for (let item of fileList) {
        if (!(item.raw.type === "image/jpeg" || item.raw.type === "image/png") || item.raw.size > 1024 * 1024 * 5) {
          errorFile.push(item);
        } else {
          successFile.push(item);
        }
      }
      for (let item of errorFile) {
        uploadImg.value.handleRemove(item);
      }
    }
    if (successFile.length <= 0) return;
  }

  FileList.value = fileList;
  for (let item of FileList.value) {
    await customUpload(item, { file: item });
  }
  const imgArr = FileList.value.map(item => {
    if (item.img) {
      return item.img;
    }
  });
  if (imgArr.length === FileList.value.length) {
    imgIsReady.value = true;
  } else {
    imgIsReady.value = false;
  }
}, 100);
/**
 * 校验文件类型
 */
const fileType = async (type, fileList) => {
  let flag = true;
  if (type === "img") {
    for (let item of fileList) {
      if (!((item.raw.type === "image/jpeg" || item.raw.type === "image/png") && item.raw.size <= 1024 * 1024 * 5)) {
        flag = false;
      }
      if (!(item.raw.type === "image/jpeg" || item.raw.type === "image/png")) {
        flag = false;
      }
    }
  } else if (type === "video") {
    for (let item of fileList) {
      // console.log("视频的大小===", item.raw.size);
      if (!(item.raw.type === "video/mp4" && item.raw.size <= 1024 * 1024 * 100)) {
        flag = false;
      }
      if (item.raw.type === "video/mp4") {
        await getTimes(item.raw);
        // console.log("视频的时长===", item.raw.size <= 1024 * 1024 * 100, videoTime.value);
        if (!(videoTime.value <= 45)) {
          flag = false;
        }
      }
    }
  }
  return flag;
};
/**
 * 获取视频时间长度
 */
const videoTime = ref(0);
const getTimes = async file => {
  let content = file;
  //获取录音时长
  let url = URL.createObjectURL(content);
  //经测试，发现audio也可获取视频的时长
  let audioElement = new Audio(url);
  console.log(2222);
  await new Promise((resolve, reject) => {
    audioElement.addEventListener("loadedmetadata", _event => {
      //保存获取时间长度
      videoTime.value = parseInt(audioElement.duration);
      resolve("时长获取成功");
    });
  });
};

/**
 * 上传
 */
const getFileName = name => {
  const arr = name.split(".");
  const _arr = JSON.parse(JSON.stringify(arr));
  let _name = "";
  let _suffix = "";
  if (arr.length > 2) {
    _arr.splice(_arr.length - 1, 1);
    _name = _arr.join(".");
    _suffix = arr[arr.length - 1];
  } else {
    _name = arr[0];
    _suffix = arr[1];
  }
  const folder = getFolder();
  return folder + _name + new Date().getTime() + "." + _suffix;
};
const customUpload = async (item, option) => {
  // 合并已上传和当前上传文件

  const objName = getFileName(option.file.name);
  await ossStore
    .submit(objName, option.file.raw)
    .then(async res => {
      await ossStore.setACL(objName, fileReadRole.publicRead);
      res.fileUrl = await ossStore.signatureUrl(objName);
      console.log("图片上传成功，地址为===", res.fileUrl.split("?")[0]);
      item["img"] = res.fileUrl.split("?")[0];
      item["folder"] = objName;
    })
    .catch(err => {
      alert(JSON.stringify(err));
    });
};
const fileReadRole = {
  defaultRole: "",
  privateRole: "private",
  publicRead: "public-read",
  publicReadWrite: "public-read-write"
};
const getLocalUrl = file => {
  if (!file?.raw) return "";
  return URL.createObjectURL(file.raw);
};
const delFileList = (item, index) => {
  FileList.value.splice(index, 1);
};
</script>

<style lang="scss" scoped>
p {
  margin: 0;
}
:deep(.el-upload-dragger) {
  background-color: #f2f3f5;
}
.el-icon--upload {
  height: auto;
  margin-bottom: 10px;
}
.file-list {
  .list-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-radius: 0px 0px 0px 0px;
    border: 1px solid #dcdfe6;
    padding: 10px;
    .left {
      display: flex;
      align-items: center;
    }
    img,
    .img {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      vertical-align: bottom;
      font-size: 24px;
    }
    &:not(:last-of-type) {
      margin-bottom: 10px;
    }
  }
}
</style>
